<?php
/********************************** Theme Custom Functions **********************************/

// width
if( !isset( $content_width ) ) $content_width = 610;

// theme support extra
add_theme_support( 'automatic-feed-links' );

// This theme styles the visual editor with editor-style.css to match the theme style.
add_editor_style( array( 'editor-style.css', 'screen.css', 'style.css' ) );

// more image cuts
if( function_exists( 'add_theme_support' ) ) { 
	add_theme_support( 'post-thumbnails' );
	add_image_size( 'featured', 288, 9999 );
	add_image_size( 'third', 208, 170, true );
	add_image_size( 'miniature', 48, 48, true );
}

// make nice numberz
function parseInt( $string ) {
	if( preg_match( '/(\d+)/', $string, $array ) ) return $array[ 1 ];
	else return 0;
}

// strip gallery css
add_filter( 'gallery_style', create_function( '$a', 'return "<div class=\'gallery\'>";' ) );

// menus WP3 only!
add_action( 'init', 'register__menus' );

function register__menus() {
	register_nav_menus(
		array(
			'main-menu' => __( 'Main Menu' ),
			'optional-menu-one' => __( 'Optional Menu One' ),
			'optional-menu-two' => __( 'Optional Menu Two' ),
			'optional-menu-three' => __( 'Optional Menu Three' ),
			'optional-menu-four' => __( 'Optional Menu Four' ),
			'optional-menu-five' => __( 'Optional Menu Five' )
		)
	);
}

// custom background
add_custom_background();

// custom header - logo
define( 'NO_HEADER_TEXT', true );
define( 'HEADER_TEXTCOLOR', '' );
define( 'HEADER_IMAGE', home_url() . '/images/logo.png' );
define( 'HEADER_IMAGE_WIDTH', 300 );
define( 'HEADER_IMAGE_HEIGHT', 70 );
function admin_header_style() {
    ?><style type="text/css">
        #logo {
            width: <?php echo HEADER_IMAGE_WIDTH; ?>px;
            height: <?php echo HEADER_IMAGE_HEIGHT; ?>px;
        }
    </style><?php
}
add_custom_image_header( 'header_style', 'admin_header_style' );

// get file size ... just for case
function getSizeFile( $url ) {
    if( substr( $url, 0, 4 ) == 'http' ) {
        $x = array_change_key_case( get_headers( $url, 1 ), CASE_LOWER );
        if( strcasecmp( $x[ 0 ], 'HTTP/1.1 200 OK' ) != 0 ) { $x = $x[ 'content-length' ][ 1 ]; }
        else { $x = $x[ 'content-length' ]; }
    } else { $x = @filesize( $url ); }
    return $x;
}

// prevent access to dashboard for all but alpha-admin
function redirect_dashboard() {
	if( !current_user_can( 'administrator' ) ) {
		wp_redirect( home_url() );
	}
}
add_action( 'admin_menu', 'redirect_dashboard' );

// nice excerpt
function avatar_continue_reading_link() {
	return ' <a href="'. get_permalink() . '" class="more-link" rel="nofollow">' . __( "...READ MORE", "sofa_suppastore" ) . '</a>';
}
function avatar_auto_excerpt_more( $more ) {
	return avatar_continue_reading_link();
}
add_filter( 'excerpt_more', 'avatar_auto_excerpt_more' );

// nested comments
function savatar_comments( $comment, $args, $depth ) {
   $GLOBALS[ 'comment' ] = $comment; 
?>

	<li id="li-comment-<?php comment_ID(); ?>">
    
    	<div class="comment-body" id="comment-<?php comment_ID(); ?>">
			
            <div class="gravatar grid_1 alpha">
               <?php
                $author_email = $comment->comment_author_email;
                echo get_avatar( $author_email, '48' );
                ?>
                <div class="reply grid_1 clearfix alpha omega">
                	<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args[ 'max_depth' ] ) ) ); ?>
                </div>
            </div>
            <div class="comment-author"><?php comment_author_link(); ?><?php edit_comment_link( 'EDIT', ' | ', '' ); ?></div>
            <div class="cmeta smaller comment-meta commentmetadata"><?php comment_date( get_option( 'date_format' ) ); ?></div>
            <?php comment_text(); ?>
            <?php if( $comment->comment_approved == '0' ) echo '<span class="hlred small">' . __( 'Your comment is awaiting moderation.' ) . '</span>'; ?>
            
        </div>
        
<?php
}

//the_content() trim
function trim_the_content( $the_contents, $read_more_tag = '...READ MORE', $perma_link_to = '', $all_words = 45 ) {
	// make the list of allowed tags
	$allowed_tags = array( 'a', 'abbr', 'b', 'blockquote', 'b', 'cite', 'code', 'div', 'em', 'fon', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'label', 'i', 'p', 'pre', 'span', 'strong', 'title', 'ul', 'ol', 'li', 'object', 'embed', 'param' );
	if( $the_contents != '' && $all_words > 0 ) {
		// process allowed tags
		$allowed_tags = '<' . implode( '><', $allowed_tags ) . '>';
		$the_contents = str_replace( ' ]]>', ' ]]>', $the_contents );
		$the_contents = strip_tags( $the_contents, $allowed_tags );
		// exclude HTML from counting words
		if( $all_words > count( preg_split( '/[\s]+/', strip_tags( $the_contents ), -1 ) ) ) return $the_contents;
		// count all
		$all_chunks = preg_split( '/([\s]+)/', $the_contents, -1, PREG_SPLIT_DELIM_CAPTURE );
		$the_contents = '';
		$count_words = 0;
		$enclosed_by_tag = false;
		foreach( $all_chunks as $chunk ) {
			// is tag opened?
			if( 0 < preg_match( '/<[^>]*$/s', $chunk ) ) $enclosed_by_tag = true;
			elseif( 0 < preg_match( '/>[^<]*$/s', $chunk ) ) $enclosed_by_tag = false;
			// get entire word
			if( !$enclosed_by_tag && '' != trim( $chunk ) && substr( $chunk, -1, 1 ) != '>' ) $count_words ++;
			$the_contents .= $chunk;
			if( $count_words >= $all_words && !$enclosed_by_tag ) break;
		}
                // note the class named 'more-link'. style it on your own
		$the_contents = $the_contents . '<a class="more-link" href="' . $perma_link_to . '" rel="nofollow">' . $read_more_tag . '</a>';
		// native WordPress check for unclosed tags
		$the_contents = force_balance_tags( $the_contents );
	}
	return $the_contents;
}

// add an extra input field to Images Repository page in order to make inserted images linkable!
function attachment_url_extra( $form_fields, $post ) {
	$this_parent = get_post( $post->post_parent );
	if( $this_parent->post_type == 'nivo-slide' ) {
		$form_fields[ 'url' ] = array(
			'label' => __( "Custom Text Field", "sofa_suppastore" ),
			'input' => 'text',
			'value' => get_post_meta( $post->ID, '_url', true )
		);
		$form_fields[ 'url' ][ 'label' ] = __( "Link this image to the following URL ", "sofa_suppastore" );
		$form_fields[ 'url' ][ 'input' ] = 'text';
		$form_fields[ 'url' ][ 'value' ] = get_post_meta( $post->ID, '_url', true );
	}
	return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'attachment_url_extra', NULL, 2 );

function attachment_url_extra_save( $post, $attachment ) {
	if( isset( $attachment[ 'url' ] ) ) {
		if( trim( $attachment[ 'url'] ) == '' ) $post[ 'errors' ][ 'url' ][ 'errors' ][] = __( "Error! Something went wrong with your link, check it out and try again.", "sofa_suppastore" );
		else update_post_meta( $post[ 'ID' ], '_url', $attachment[ 'url' ] );
	}
	return $post;
}
add_filter( 'attachment_fields_to_save', 'attachment_url_extra_save', NULL, 2 );

// auto install plugins
if( is_admin() && isset( $_GET[ 'activated' ] ) && $pagenow == 'themes.php' ) {

	$theme_url = get_template_directory_uri();
	$theme_url_split = explode( '/', $theme_url );
	$theme_url_split_length = count( $theme_url_split );
	$theme_name = $theme_url_split[ $theme_url_split_length - 1 ];
	
	// epicwin
	$newsletter_source = '../wp-content/themes/' . $theme_name . '/plugins/epicwin-subscribers';
	$newsletter_target = '../wp-content/plugins/epicwin-subscribers';
	$plugin_newsletter = 'epicwin-subscribers/epicwin.php';
	
	// colorbox
	$colorbox_source = '../wp-content/themes/' . $theme_name . '/plugins/jquery-colorbox';
	$colorbox_target = '../wp-content/plugins/jquery-colorbox';
	$plugin_colorbox = 'jquery-colorbox/jquery-colorbox.php';
	
	function plugin_copy( $source, $target, $plugin_dir ) {
		
		if ( is_dir( $source ) ) {
			@mkdir( $target );
			$d = dir( $source );
			while( FALSE !== ( $entry = $d->read() ) ) {
				if ( $entry == '.' || $entry == '..' ) continue;
				$Entry = $source . '/' . $entry; 
				if ( is_dir( $Entry ) ) {
					plugin_copy( $Entry, $target . '/' . $entry, $plugin_newsletter );
					continue;
				}
				copy( $Entry, $target . '/' . $entry );
			}
			$d->close();
			
			// if( $plugin_dir == 'epicwin-subscribers/epicwin.php' ) activate_nl_plugin( $plugin_dir ); // don't activate automatically
			
			if( $plugin_dir == 'jquery-colorbox/jquery-colorbox.php' ) activate_cb_plugin( $plugin_dir );
		}
		
	}

	function activate_nl_plugin( $plugin_newsletter ) {
		
		if( !file_exists( ABSPATH . '/wp-content/plugins/' . $plugin_newsletter ) ) return;
		
		$current = get_option( 'active_plugins' );
		$plugin_newsletter = plugin_basename( trim( $plugin_newsletter ) );
		if( !in_array( $plugin_newsletter, $current ) ) {
			$current[] = $plugin_newsletter;
			sort( $current );
			do_action( 'activate_plugin', trim( $plugin_newsletter ) );
			update_option( 'active_plugins', $current );
			do_action( 'activate_' . trim( $plugin_newsletter ) );
			do_action( 'activated_plugin', trim( $plugin_newsletter ) );
		}

	}
	
	function activate_cb_plugin( $plugin_colorbox ) {
		
		if( !file_exists( ABSPATH . '/wp-content/plugins/' . $plugin_colorbox ) ) return;
		
		$current = get_option( 'active_plugins' );
		$plugin_colorbox = plugin_basename( trim( $plugin_colorbox ) );
		if( !in_array( $plugin_colorbox, $current ) ) {
			$current[] = $plugin_colorbox;
			sort( $current );
			do_action( 'activate_plugin', trim( $plugin_colorbox ) );
			update_option( 'active_plugins', $current );
			do_action( 'activate_' . trim( $plugin_colorbox ) );
			do_action( 'activated_plugin', trim( $plugin_colorbox ) );
		}

	}
	
	//Include Newsletter plugin
	plugin_copy( $newsletter_source, $newsletter_target, $plugin_newsletter );
	
	//Include Colorbox plugin
	plugin_copy( $colorbox_source, $colorbox_target, $plugin_colorbox );
}